#include "game.h"

Game::Game(){
	board = new Board();
	//White
	for(int i = 0; i < 8; i++){
		pieces[i] = new Pawn(Piece::WHITE,2,i+1);
	}
	pieces[8] = new Rook(Piece::WHITE, 1,1);
	pieces[9] = new Rook(Piece::WHITE,1,8);
	pieces[10] = new Knight(Piece::WHITE,1,2);
	pieces[11] = new Knight(Piece::WHITE,1,7);
	pieces[12] = new Bishop(Piece::WHITE,1,3);
	pieces[13] = new Bishop(Piece::WHITE,1,6);
	pieces[14] = new King(Piece::WHITE, 1,5);
	pieces[15] = new Queen(Piece::WHITE, 1,4);

	//Black
	for(int i = 16; i < 24; i++){
		pieces[i] = new Pawn(Piece::BLACK,7,i-15);
	}
	pieces[24] = new Rook(Piece::BLACK, 8,1);
	pieces[25] = new Rook(Piece::BLACK, 8,8);
	pieces[26] = new Knight(Piece::BLACK,8,2);
	pieces[27] = new Knight(Piece::BLACK,8,7);
	pieces[28] = new Bishop(Piece::BLACK,8,3);
	pieces[29] = new Bishop(Piece::BLACK,8,6);
	pieces[30] = new King(Piece::BLACK, 8,5);
	pieces[31] = new Queen(Piece::BLACK, 8,4);
}

void Game::drawGame(){
	// Draw the board including squares
	board->drawBoard();

	// Draw each piece
	for(int i = 0; i < 32; i++){
		pieces[i]->drawPiece();
	}
}

void Game::selectPiece(int file, int rank){
	// Only allow user to select squares that contain pieces
	for(int i = 0; i < 32; i++){
		if(pieces[i]->file == file && pieces[i]->rank == rank){
			// Select the square
			Square::select(file, rank);
			return;
		}
	}

	Square::unselect();
}

void Game::mouseCollide(int x, int y)
{
	GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;
 
    glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
    glGetDoublev( GL_PROJECTION_MATRIX, projection );
    glGetIntegerv( GL_VIEWPORT, viewport );
 
    winX = (float)x;
    winY = (float)viewport[3] - (float)y;
    glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
 
    gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

	selectPiece((int)posX + 1, (int)posZ + 1);
}